package com.x2.modular.demo.test.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.x2.base.pojo.page.LayuiPageFactory;
import com.x2.base.pojo.page.LayuiPageInfo;
import com.x2.core.util.ToolUtil;
import com.x2.modular.demo.test.entity.Order;
import com.x2.modular.demo.test.mapper.OrderMapper;
import com.x2.modular.demo.test.model.OrderBean;
import com.x2.modular.demo.test.service.IOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * @Version 1.0
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Override
    @DSTransactional(rollbackFor = Exception.class)
    public void add(OrderBean param) throws Exception {
        Order entity = getEntity(param);
        this.save(entity);
        if (param.getCount() > 1000) {
            throw new Exception("xxxx1");
        }
    }

    @Override
    @DSTransactional(rollbackFor = Exception.class)
    public void update(OrderBean param) throws Exception {
        Order newEntity = getEntity(param);
        this.updateById(newEntity);
    }

    @Override
    @DSTransactional(rollbackFor = Exception.class)
    public void delete(OrderBean param) throws Exception {
        this.removeById(getKey(param));
    }

    @Override
    public OrderBean findBySpec(OrderBean param) {
        List<OrderBean> list = baseMapper.queryList(param);
        if (list == null || list.size() == 0) {
            return null;
        }
        return list.get(0);
    }


    @Override
    public List<OrderBean> findListBySpec(OrderBean param) {
        return baseMapper.queryList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(OrderBean param) {
        Page pageContext = getPageContext();
        pageContext.addOrder(OrderItem.desc("t.create_time"));
        IPage page = this.baseMapper.queryPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }


    private Serializable getKey(OrderBean param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Order getEntity(OrderBean param) {
        Order entity = new Order();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}

